<template>
  <transition>
    <div class="car-item" v-if="selfIndex === currentIndex">
      <slot></slot>
    </div>
  </transition>
</template>

<script>
//获取当前组件实例
import { getCurrentInstance, reactive, toRefs, watch } from "vue";

export default {
  name: "CarItem",
  setup() {
    const instance = getCurrentInstance();
    // console.log(instance);
    //组件实例

    const state = reactive({
      // instance.vnode.key -> 拿到当前组件自身index
      selfIndex: instance.vnode.key,
      //instance.parent.ctx.currentIndex -> 拿到父组件执行期上下文里定义的currentIndex
      //注意：这里拿到的instance.parent.ctx.currentIndex并不是响应式数据
      //可以通过监听的方式实现数据响应式
      currentIndex: instance.parent.ctx.currentIndex,
    });

    watch(
      () => {
        return instance.parent.ctx.currentIndex;
      },
      (value) => {
        //将监听返回的value赋值给响应式数据的state.currentIndex实现数据响应处理
        state.currentIndex = value;
      }
    );

    return {
      ...toRefs(state),
    };
  },
};
</script>

<style lang="scss" scoped>
.car-item {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.v-enter-active,
.v-leave-active {
  transition: all 0.3s linear;
}

.v-enter-active {
  transform: translateX(100%);
}

.v-enter-to {
  transform: translateX(0);
}

.v-leave-active {
  transform: translateX(0);
}

.v-leave-to {
  transform: translateX(-100%);
}
</style>